import axios from 'axios'
import { ElMessage } from 'element-plus'

const api = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 未授权，清除token并跳转到登录页
          localStorage.removeItem('token')
          window.location.href = '/login'
          break
        case 403:
          // 权限不足
          ElMessage.error('没有权限访问')
          break
        case 500:
          // 服务器错误
          ElMessage.error('服务器错误，请稍后重试')
          break
        default:
          ElMessage.error(error.response.data.message || '请求失败')
      }
    }
    return Promise.reject(error)
  }
)

export const login = data => {
  return api.post('/auth/login', data)
}

export const register = data => {
  return api.post('/auth/register', data)
}

export const getUserInfo = () => {
  return api.get('/user/info')
}

export const updateUserInfo = data => {
  return api.put('/user/info', data)
}

export const getFriendList = () => {
  return api.get('/friend/list')
}

export const addFriend = friendId => {
  return api.post('/friend/add', { friendId })
}

export const deleteFriend = friendId => {
  return api.delete(`/friend/${friendId}`)
}

export const getPosts = params => {
  return api.get('/post/list', { params })
}

export const createPost = data => {
  return api.post('/post/create', data)
}

export const likePost = postId => {
  return api.post(`/post/${postId}/like`)
}

export const commentPost = (postId, content) => {
  return api.post(`/post/${postId}/comment`, { content })
}

export const getComments = postId => {
  return api.get(`/post/${postId}/comments`)
}

export const deleteComment = commentId => {
  return api.delete(`/post/comment/${commentId}`)
}

export const searchUsers = nickname => {
  return api.get('/user/search', {
    params: { nickname }
  })
}

export const getDashboardStats = () => {
  return api.get('/admin/dashboard/stats')
}

// K匿名配置相关API
export const getKAnonymityConfigs = () => {
  return api.get('/admin/k-anonymity/list')
}

export const getCurrentKAnonymityConfig = () => {
  return api.get('/admin/k-anonymity/current')
}

export const createKAnonymityConfig = (data) => {
  return api.post('/admin/k-anonymity', data)
}

export const updateKAnonymityConfig = (data) => {
  return api.put('/admin/k-anonymity', data)
}

export const toggleKAnonymityConfig = (id, enabled) => {
  return api.put(`/admin/k-anonymity/${id}/toggle?enabled=${enabled}`)
}

export const deleteKAnonymityConfig = (id) => {
  return api.delete(`/admin/k-anonymity/${id}`)
}

export default api 